<template>
  <view>
    <view class="bgView flexStandard">
      <view class="titleBox">
        <view class="titleView"><text class="title">钱包余额</text></view>
        <view
          ><text class="num">{{ moneyval }}</text></view
        >
      </view>
    </view>

    <view class="czhiView">
      <text>充值金额</text>
    </view>

    <view class="flexCenten">
      <view class="btnView">
        <view
          :class="[true && 'flexCenten', activeIndex == index && 'active']"
          v-for="(item, index) in numArray"
          :key="index"
          @tap="activethis"
          :data-thisindex="index"
        >
          <text v-if="item != 'm'" class="otherText" :data-thisindex="index"
            >￥{{ item }}</text
          >
          <text
            v-if="item == 'm' && activeIndex != index"
            class="zidyText"
            :data-thisindex="index"
            >自定义金额</text
          >
          <input
            v-if="item == 'm' && activeIndex == index"
            focus
            class="weui-input inputView"
            placeholder="请输入金额"
            v-model="money"
          />
        </view>
      </view>
    </view>
  </view>

  <view class="czhiBox flexStandard" @tap="paymoney">
    <view class="btnczhi flexCenten">
      <text>立即充值</text>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import { getMoneyAPI, putMoneyAPI, gteMoneyOrderAPI } from "@/services/wallet";
import { useMemberStore } from "@/stores";
import { onReady } from "@dcloudio/uni-app";
import type { PaymentParams } from "@/types/order";

const money = ref(20); //默认选中第一个
const activeIndex = ref(0); //默认选中第一个
const numArray = ref([20, 30, 50, 80, 100, "m"]);

const moneyval = ref("0");

// 定义正则表达式，用于匹配正确的金额格式
function isValidNumber(amountStr: any) {
  // 不允许带有前导零的整数部分（但允许0.xx形式的小数）
  const regex = /^(0|[1-9]\d*)(\.\d{1,2})?$/;

  // 检查输入是否为空或不符合正则表达式
  if (!amountStr || !regex.test(amountStr)) {
    return false;
  }

  // 将输入转换为浮点数进行精确判断
  const amount = parseFloat(amountStr);

  // 校验金额是否大于等于0.01
  if (amount < 0.01) {
    return false;
  }

  // 所有条件都满足，则返回true
  return true;
}

const memberStore = useMemberStore();

//获取用户余额
async function getmoney() {
  if (memberStore.profile) {
    const res = await getMoneyAPI();
    // const resdd = await putMoneyAPI()
    if (res.code == "200") {
      moneyval.value = res.data.money;
    }
  }
}

//页面首次加载调用
onReady(() => {
  getmoney();
});

// 获取支付数据
// 获取订单信息
const paymentdata = ref<{
  orderInfo: string;
  timeStamp: string;
  nonceStr: string;
  package: string;
  paySign: string;
}>({
  orderInfo: "",
  timeStamp: "",
  nonceStr: "",
  package: "",
  paySign: "",
});

//发起微信支付
const getPaymentData = async () => {
  try {
    if (money.value) {
      const res = await gteMoneyOrderAPI(money.value);
      paymentdata.value = res.result;
      // 发起支付
      uni.requestPayment({
        provider: "wxpay",
        orderInfo: paymentdata.value.orderInfo,
        timeStamp: paymentdata.value.timeStamp.toString(),
        nonceStr: paymentdata.value.nonceStr,
        package: paymentdata.value.package,
        signType: "RSA",
        paySign: paymentdata.value.paySign,
        success: async function (res) {
          //更新订单状态为待送达
          // putMemberOrderPreData()
          // 关闭当前页，再跳转支付结果页
          await putMoneyAPI(money.value);
          getmoney();
          uni.$emit("closeCart");
          uni.$emit("refreshMealList");
          uni.navigateBack();
          // uni.redirectTo({ url: `/pagesOrder/payment/payment?order_id=${orderId.value}` })
          console.log("success:" + JSON.stringify(res));
        },
        fail: function (err) {
          //提醒支付异常
          // 成功提示
          uni.showToast({
            title: "支付异常",
            duration: 1000,
            success: () => {
              setTimeout(() => {
                //查询订单有效性
                //deletetMemberOrderPreData()
                // 关闭当前清单，并跳转到首页
                uni.$emit("closeCart");
                uni.$emit("refreshMealList");
                // uni.navigateBack()
                // uni.redirectTo({ url: '/pages/wallet/wallet' })
              }, 1000);
            },
          });
          console.log("fail:" + JSON.stringify(err));
        },
      });
    }
  } catch (error) {
    //TODO handle the exception
    uni.showToast({
      title: "网络错误",
      duration: 1000,
    });
  }
};

//充值余额的选择
const activethis = (event: any) => {
  const thisindex = event.currentTarget.dataset.thisindex; //当前ind
  activeIndex.value = thisindex;
  if (thisindex !== 5) {
    money.value = numArray.value[thisindex] as number;
  } else {
    money.value = 0;
  }
};

//验证输入框是否是有效数字
const paymoney = () => {
  // console.log(money.value);

  if (money.value) {
    if (!isValidNumber(money.value)) {
      uni.showToast({
        title: "请输入有效数字",
        icon: "none",
        duration: 1500,
      });
      return;
    }
  }
  if (!money.value) {
    uni.showToast({
      title: "请输入充值数额",
      icon: "none",
      duration: 1500,
    });
    return;
  }

  getPaymentData();
};
</script>

<style lang="scss">
.active {
  background-image: linear-gradient(130deg, #00cfab 60%, #7bfaa5 100%);
  border: 2px solid #00cca8;
  color: white;
}

.noactive {
  background-color: white;
  border: 2px solid white;
  color: black;
}

.btnView {
  width: 100%;
  height: 300rpx;
  display: flex;
  flex-wrap: wrap;
  align-content: flex-start;
  justify-content: center;
}

.btnView view {
  width: 210rpx;
  height: 100rpx;
  margin: 10rpx;
  border-radius: 10rpx;
}

.otherText {
  /* color: black; */
  font-size: 38rpx;
  font-weight: 600;
}

.inputView {
  height: 100%;
  width: 100%;
  text-align: center;
  font-size: 38rpx;
  color: white;
}

.zidyText {
  font-size: 30rpx;
  font-weight: 600;
}

.bgView {
  background-image: linear-gradient(120deg, #84fab0 0%, #8fd3f4 100%);
  height: 150rpx;
  width: 100%;
  margin-bottom: 30rpx;
}

.titleBox {
  text-align: center;
}

.title {
  color: white;
  font-size: 28rpx;
}

.titleView {
  margin-bottom: 20rpx;
}

.num {
  color: white;
  font-size: 40rpx;
  font-weight: 600;
}

.czhiView {
  width: 100%;
  height: 100rpx;
  background-color: white;
  padding: 0rpx 30rpx;
  margin-bottom: 10rpx;
}

.czhiView text {
  font-size: 28rpx;
}

.czhiBox {
  width: 100%;
}

.btnczhi {
  width: 94%;
  background-color: #1aad19;
  height: 80rpx;
  border-radius: 10rpx;
  text-align: center;
  line-height: 80rpx;
  margin: 0 auto;
}

.btnczhi text {
  color: white;
  font-size: 32rpx;
}
</style>
